package httpMiddleware

import (
	"errors"
	"github.com/gin-gonic/gin"
	"go_gateway/dao"
	"go_gateway/middleware"
	reverseProxy "go_gateway/reverse_proyx"
)

// HTTPReverseProxyMiddleware
// @Description: HTTP反向代理实现中间件
// @return gin.HandlerFunc
//
func HTTPReverseProxyMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 1.从ctx中获取service
		serviceInterface, ok := c.Get("service")
		if !ok {
			middleware.ResponseError(c, 2001, errors.New("service not found"))
			c.Abort()
			return
		}

		serviceDetail := serviceInterface.(*dao.ServiceDetail)

		// 2.根据service获取负载均衡器
		loadBalancer, err := dao.LoadBalancerManager.GetLoadBalancer(serviceDetail)
		if err != nil {
			middleware.ResponseError(c, 2002, err)
			c.Abort()
			return
		}
		// 3.根据service获取连接配置
		transporter, err := dao.TransporterManager.GetTransporter(serviceDetail)
		if err != nil {
			middleware.ResponseError(c, 2003, err)
			c.Abort()
			return
		}
		// 4.生成反向代理
		//TODO: 权重负载均衡失效
		proxy := reverseProxy.NewLoadBalanceReverseProxy(c, loadBalancer, transporter)
		proxy.ServeHTTP(c.Writer, c.Request)
		c.Abort()
		return
	}
}
